/**
 * 课程表主组件
 */

'use client';

import React, { useState, useMemo } from 'react';
import { useCourseData } from '../../hooks/useCourseData';
import { useWeekCalculation } from '../../hooks/useWeekCalculation';
import { useColorAllocation } from '../../hooks/useColorAllocation';
import { useStaggeredAnimation } from '../../hooks/useStaggeredAnimation';
import { CourseCard } from './CourseCard';
import { WeekSelector } from './WeekSelector';
import { CountdownTimer } from './CountdownTimer';
import { CourseDetailModal } from './CourseDetailModal';
import { filterCoursesByWeek, TIME_SLOTS } from '../../utils/scheduleUtils';
import { getWeekDayHeaders, getMonthName } from '../../utils/dateUtils';
import { ProcessedCourse } from '../../types/course';
import { Menu } from 'lucide-react';
import { clsx } from 'clsx';

export const CourseSchedule: React.FC = () => {
  const [selectedCourse, setSelectedCourse] = useState<ProcessedCourse | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isWeekSelectorOpen, setIsWeekSelectorOpen] = useState(false);
  
  // 数据管理
  const { courseSchedule, courses, loading, error } = useCourseData();
  
  // 周次计算
  const {
    currentWeek,
    setCurrentWeek,
    availableWeeks,
    daysUntilEnd
  } = useWeekCalculation(
    courseSchedule?.startDate || '2025-09-01',
    courses
  );
  
  // 过滤当前周的课程
  const weekCourses = useMemo(() => {
    return filterCoursesByWeek(courses, currentWeek);
  }, [courses, currentWeek]);
  
  // 颜色分配
  const { processedCourses } = useColorAllocation(weekCourses);

  // 交错动画管理
  const { animationKey, getDelay } = useStaggeredAnimation(processedCourses.length, [currentWeek]);
  
  
  // 获取当前周的日期信息
  const dayHeaders = useMemo(() => {
    if (!courseSchedule) return [];
    return getWeekDayHeaders(new Date(courseSchedule.startDate), currentWeek);
  }, [courseSchedule, currentWeek]);
  
  // 获取当前月份
  const currentMonth = useMemo(() => {
    if (!courseSchedule) return '';
    const startDate = new Date(courseSchedule.startDate);
    const currentDate = new Date(startDate);
    currentDate.setDate(currentDate.getDate() + (currentWeek - 1) * 7);
    return getMonthName(currentDate);
  }, [courseSchedule, currentWeek]);
  
  // 处理课程卡片点击
  const handleCourseClick = (course: ProcessedCourse) => {
    setSelectedCourse(course);
    setIsModalOpen(true);
  };
  
  // 处理周次变化
  const handleWeekChange = (week: number) => {
    setCurrentWeek(week);
  };
  
  // 加载状态
  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p className="text-gray-600">加载课程数据中...</p>
        </div>
      </div>
    );
  }
  
  // 错误状态
  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-red-50 to-pink-100 flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">加载课程数据失败</p>
          <p className="text-gray-600 text-sm">{error}</p>
        </div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
      {/* 顶部导航栏 */}
      <header className="sticky top-0 z-20 bg-white/10 backdrop-blur-md border-b border-white/20">
        <div className="container mx-auto px-4 py-3">
          <div className="flex items-center justify-between">
            {/* 左侧菜单按钮 */}
            <button className="p-2 rounded-lg text-gray-400 cursor-not-allowed">
              <Menu className="w-6 h-6" />
            </button>
            
            {/* 中部周次选择器 */}
            <WeekSelector
              isOpen={isWeekSelectorOpen}
              onOpenChange={setIsWeekSelectorOpen}
              currentWeek={currentWeek}
              availableWeeks={availableWeeks}
              onWeekChange={handleWeekChange}
            />
            
            {/* 右侧预留空间 */}
            <div className="w-10"></div>
          </div>
        </div>
      </header>
      
      {/* 课程表主体 */}
      <main className={clsx(
        "container mx-auto px-4 py-6 transition-all duration-300",
        (isWeekSelectorOpen || isModalOpen) && "blur-sm pointer-events-none"
      )}>
        <div className="bg-white rounded-xl shadow-lg overflow-hidden">
          {/* 课程表网格 */}
          <div key={animationKey} className="schedule-grid grid grid-cols-8 grid-rows-7 gap-1 p-4">
            {/* 第一行：表头 */}
            <div className="schedule-header-month bg-gray-100 rounded-lg flex items-center justify-center text-sm font-medium text-gray-700">
              {currentMonth}
            </div>
            
            {dayHeaders.map((day) => (
              <div
                key={day.day}
                className={clsx(
                  'schedule-header-day rounded-lg flex flex-col items-center justify-center text-sm font-medium transition-all',
                  day.isToday
                    ? 'bg-blue-500 text-white shadow-lg'
                    : 'text-gray-700'
                )}
              >
                <div>{day.dayName}</div>
                {day.isToday && (
                  <div className="text-xs opacity-90">{day.date}</div>
                )}
              </div>
            ))}
            
            {/* 时间段和课程内容 */}
            {TIME_SLOTS.map((timeSlot, rowIndex) => (
              <React.Fragment key={timeSlot.id}>
                {/* 时间段标签 */}
                <div className="schedule-time-slot bg-gray-100 rounded-lg flex items-center justify-center text-sm font-medium text-gray-700">
                  <span className="hidden sm:inline">{timeSlot.label}</span>
                  <span className="sm:hidden time-text text-xs">
                    {timeSlot.label.split('-').map((part, index) => (
                      <React.Fragment key={index}>
                        {index > 0 && <br />}
                        {part}
                      </React.Fragment>
                    ))}
                  </span>
                </div>
                
                {/* 每天的课程单元格 */}
                {Array.from({ length: 7 }, (_, dayIndex) => {
                  const dayOfWeek = dayIndex + 1;
                  const coursesInSlot = processedCourses.filter(course => {
                    const courseStartSlot = Math.floor((course.section.start - 1) / 2);
                    return course.week === dayOfWeek && courseStartSlot === rowIndex;
                  });
                  
                  return (
                    <div
                      key={`${rowIndex}-${dayIndex}`}
                      className="schedule-cell relative min-h-[60px] rounded-lg border border-gray-200 hover:border-gray-300 transition-colors"
                    >
                      {processedCourses.filter(c => c.week === dayOfWeek && Math.floor((c.section.start - 1) / 2) === rowIndex).map((course, index) => (
                        <CourseCard
                          key={`${course.courseName}-${course.section.start}`}
                          course={course}
                          onClick={handleCourseClick}
                          animationDelay={getDelay(processedCourses.findIndex(c => c.courseName === course.courseName && c.section.start === course.section.start))}
                          className="absolute inset-0"
                        />
                      ))}
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      </main>
      
      {/* 倒计时组件 */}
      <CountdownTimer daysRemaining={daysUntilEnd} />
      
      {/* 课程详情模态框 */}
      <CourseDetailModal
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
        course={selectedCourse}
      />
    </div>
  );
};
